<?php
namespace App\Http\Controllers\Web\User;

use App\Http\Controllers\Web\BaseController;
use App\Services\Cookie\Carts;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Http\Request;
use Jenssegers\Agent\Facades\Agent;
use Illuminate\Support\Facades\Cookie;

class UserController extends BaseController
{
    protected  $api_url = [
        'login' => ['get', 'user/login'],
        'old_login' => ['get', 'userinfo/login'],
        //'messageslogin' => ['get', 'user/messageslogin'],
        'old_messageslogin' => ['get', 'userinfo/messages-login'],
        'sendmessage' => ['get', 'sendmessage'], 
        'checkphone' => ['get', 'user/checkphone'],
        'checkusername' => ['get', 'user/checkusername'],
        'messageslogin' => ['get', 'user/messageslogin'], 
        'verifycode' => ['get', 'verifycode'],
        'backpwd' => ['get', 'user/backpwd'],
        'cate' => ['get', 'cate'],
        'companyregister' => ['post', 'user/companyregister'],
        'personalregister' => ['post', 'user/personalregister'],
        'add_carts'=> ['post', 'buyer/carts/add_carts'],
        'verify_im'=> ['post', 'im/verify'], // 登录成功后验证账号是否有 IM 账号

    ];


    protected $request;

    public function __construct(Request $request)
    {
        //设备类型
         if (Agent::isTablet()) {
          // 平板
             $equipment = 'Tablet';
         } else if (Agent::isMobile()) {
          // 便捷设备
             $equipment = 'Mobile';
         } else if (Agent::isRobot()) {
          // 爬虫机器人
             $equipment = 'Robot';
         } else {
          // 桌面设备
             $equipment = 'Desktop';
         }

        $this->request = $request;
        $this->ip = $request->getClientIp() ? $request->getClientIp() : '127.0.0.1';
        $this->logn_equipment = $equipment;
        $this->to_url = '/member/user/info';
    }


    //登陆视图页
    public function loginAction(){
        if (session('user_id') && session('user_id')!=''){
            return redirect($this->to_url);

        }

        $PreviousStep = $this->request->headers->get('referer');        
        $parse_arr = parse_url($PreviousStep);
        if(!(isset($parse_arr['path']) && $parse_arr['path']) || strpos($PreviousStep,'/user/register') !== false){
            if(session('login_source_page')){
                //如果session中存在来源页，则使用session中的来源页
                $PreviousStep = session('login_source_page');
            }else{
                $PreviousStep = asset($this->to_url);
            }
        }else{
            //如果当前来源页存在，则重新存储来源页面
            session(['login_source_page' => $PreviousStep]);
        }        
        

        return view('web.login.login')->with(['PreviousStep'=>$PreviousStep]);
    }


    /*
     * 用户登录处理
     */
    public function loginmemberAction(Carts $carts_server)
    {
        $this->validate($this->request, [
            'uname' => 'required|string',
            'pwd' => 'required|string'
        ]); 
        $all = $this->request->all('uname','pwd');

         //请求部分  
        $postzhi = array('username' => $all['uname'], 'pwd' => $all['pwd'],'ip' => $this->ip,'logn_equipment' => $this->logn_equipment);
        $data = http_web($this->api_url['login'])->send($postzhi);

        if ($data['code'] == 0) {
            /*try{
                $old_zhi = ['name'=>$all['uname'],'pwd'=>$all['pwd']];
                $old_data = http_old_web($this->api_url['old_login'])->send($old_zhi);
            }catch (\Exception $e){
                return response(json_encode(['code'=>1,'message'=>'错误']));
            }*/
            try{
                $verify = [
                    'user_id'=>$data['data']['id'],
                    'password'=>'123456',
                ];
                $im = http_web($this->api_url['verify_im'])->send($verify);
                //dd($im);
            }catch (\Exception $e){
            }

            //将登陆信息注入session
            session([
                'user_id' => $data['data']['id'],
                'user_phone' => $data['data']['phone'],
                'user_name' => $data['data']['name'],
                'user_email' => $data['data']['email'],
                'user_shop_id' => $data['data']['shop_id'],
                'user_is_test_user' => $data['data']['is_test_user'],
                'user_identification_type' => $data['data']['identification_type'],
                'user_personal_enterprise' => $data['data']['personal_enterprise'],
                'user_b2b_token' => $data['data']['user_token'],
                //'usertoken' => $old_data['data']['token'],
                'user_info' => $data['data'],
                'user_im_token' => isset($im['data']['data']['token'])?$im['data']['data']['token']:false,
                'user_im_name' => isset($im['data']['data']['accid'])?$im['data']['data']['accid']:false,
                //'userinfo' => $old_data['data']
            ]);
            //清空来源页
            session(['login_source_page' => '']);

            //合并cookie 获取cookie当中购物车数据
            $cart_arr=$carts_server->getList();
            if(!empty($cart_arr)){
                if(isset($cart_arr[0]['user_id'])){
                    $cart_arr=[];
                }
            }
            $ret = http_web($this->api_url['add_carts'])->send(['data'=>$cart_arr]);
            $cookie_data=serialize($ret['data']);
            Cookie::queue('carts_data_arr',$cookie_data);

        } 
        return response(json_encode($data));

//        return $data;
        
    }


    /*
     * 直接用短信登录处理
     */
    public function messagesLoginAction(Carts $carts_server)
    {
        $this->validate($this->request, [
            'phone' => 'required|numeric',
            'phoneverify' => 'required'
        ]); 

        $all = $this->request->all('phone','phoneverify');

        //登陆请求验证
        $param = ['username' => $all['phone'], 'key' => md5('ejing365'),'code' => $all['phoneverify'],'ip' => $this->ip,'logn_equipment' => $this->logn_equipment];
        $data = http_web($this->api_url['messageslogin'])->send($param);
        if ($data['code'] == 0) {
            /*try{
                $old_zhi = ['name'=>$all['phone'],'key'=>md5('ejing365'),'code' => $all['phoneverify']];
                $old_data = http_old_web($this->api_url['old_messageslogin'])->send($old_zhi);
            }catch (\Exception $e){
                return response(json_encode(['code'=>1,'message'=>'错误']));
            }*/
            //将登陆信息注入session
            session([
                'user_id' => $data['data']['id'],
                'user_phone' => $data['data']['phone'],
                'user_name' => $data['data']['name'],
                'user_email' => $data['data']['email'],
                'user_shop_id' => $data['data']['shop_id'],
                'user_is_test_user' => $data['data']['is_test_user'],
                'user_identification_type' => $data['data']['identification_type'],
                'user_personal_enterprise' => $data['data']['personal_enterprise'],
                'user_b2b_token' => $data['data']['user_token'],
                //'usertoken' => $old_data['data']['token'],
                'user_info' => $data['data'],
                //'userinfo' => $old_data['data']
            ]);
            session(['login_source_page' => '']);

            //合并cookie 获取cookie当中购物车数据
            $cart_arr=$carts_server->getList();
            if(!empty($cart_arr)){
                if(isset($cart_arr[0]['user_id'])){
                    $cart_arr=[];
                }
            }
            $ret = http_web($this->api_url['add_carts'])->send(['data'=>$cart_arr]);
            $cookie_data=serialize($ret['data']);
            Cookie::queue('carts_data_arr',$cookie_data);

        }
        return $data;
    }



    /*
    *发送短信
    */
    public function sendmessagesAction(Request $request)
    {
        $phone = $request->input('phone');
        if (!preg_match("/^1[34578]\d{9}$/", $phone)) {
            $data['code'] = '1';
            $data['message'] = '手机号码格式不正确';
        } else {
            //验证是否注册             
            $param = ['phone' => $phone];
            $data = http_web($this->api_url['checkphone'])->send($param);

            if ($data['data'] === 902) {
                //发送短信验证
                $data_send = http_web($this->api_url['sendmessage'])->send($param);

               return $data_send;

            } else {
                $data['code'] = '1';
                $data['message'] = $data['message'];
            }

        }
        return response()->json($data);

    }





    /*
    *找回密码视图
    */
    public function forgetAction(Request $request){
        if (session('user_id'))
            return redirect($this->to_url);
        $data = $request->all('uname','code','message');

        return view('web.login.forget')->with(['data' => $data]);
    }


    /*
    *找回密码---录入新密码视图
    */
    public function forgettwoAction(Request $request){
       if (session('user_id'))
            return redirect($this->to_url);
        $this->validate($this->request, [
            'uname' => 'required|numeric',
            'captcha' => 'required|numeric'
        ]); 

        $all = $request->all('uname','captcha');

        $phone = $all['uname'] ? $all['uname'] : '';
        $captcha = $all['captcha'] ? $all['captcha'] : '';

        $param = ['phone' => $phone,'code' => $captcha];
        $data = http_web($this->api_url['verifycode'])->send($param);
        if($data['code'] == 0){
            return view('web.login.forget2')->with(['data'=>$param]);
        }else{
            return redirect('/user/forget?uname='.$phone.'&code='.$captcha.'&message='.$data['message']);
        }
        
       
    }



     /*
     * 找回密码修改密码
     */
    public function forgetupdateAction(Request $request)
    {

        $this->validate($this->request, [
            'name' => 'required|numeric',
            'pwd' => 'required'
        ]); 

        $all = $this->request->all('name','pwd');

        //修改请求验证
        $param = ['phone' => $all['name'], 'key' => md5('ejing365'),'pwd' => $all['pwd'],'ip' => $this->ip,'logn_equipment' => $this->logn_equipment];
        $data = http_web($this->api_url['backpwd'])->send($param);

        return $data;

    }







    /*
    *注册短信发送，判断方式和其他发送短信相反
    */
    public function registermessagesAction(Request $request)
    {
        $phone = $request->input('phone');
        if (!preg_match("/^1[34578]\d{9}$/", $phone)) {
            $data['code'] = '1';
            $data['message'] = '手机号码格式不正确';
        } else {
            //验证是否注册
            $param = ['phone' => $phone];
            $data = http_web($this->api_url['checkphone'])->send($param);

            if ($data['data'] === 903) {
                //发送短信验证
                $data_send = http_web($this->api_url['sendmessage'])->send($param);

                return $data_send;

            } else {
                $data['code'] = '1';
                $data['message'] = $data['message'];
            }

        }
        return response()->json($data);

    }





    //注册视图页
    public function registerAction(){
        if (session('user_id'))
            return redirect($this->to_url);

        // 主营行业 商品一级分类
        $params = [
            'search' => 'pid:0',
            'searchJoin' => 'and',
            'type' => 'all'
        ];
        $cate_data = http_web($this->api_url['cate'])->send($params);
        $business_trade = $cate_data['data']['list'];

        return view('web.login.register')->with(['business_trade'=>$business_trade]);
    }




     /*
     * 企业注册信息提交
     */
    public function companyRegisterAction(Request $request)
    {
        $this->validate($this->request, [
            'name' => 'required|string',
            'company_type' => 'required|string',
            //'business' => 'required|string',
            'contacts' => 'required|string',
            'phone' => 'required|string',
            'pwd' => 'required|string',
            'code' => 'required|string',
        ]);

     /*   //验证组织机构代码是否存在（当做会员登录用户名）
        $param_jigou = ['organization_code' => $request->input('organizationCode')];
        $data_jigou = http_web($this->api_url['checkusername'])->send($param_jigou);

        if ($data_jigou['data'] != 903) {
            $data_jg['code'] = '1';
            $data_jg['message'] = $data_jigou['message'];

            return $data_jg;

        }*/

        //验证验证码是否填写正确
        $param_code = ['phone' => $request->input('phone'),'code' => $request->input('code')];
        $data_code = http_web($this->api_url['verifycode'])->send($param_code);
        if($data_code['code'] != 0){
            return $data_code;
        }
        //参数
        //$referee = $request->input('referee');
        $params = [
            'phone' => $request->input('phone'),
            'pwd' => $request->input('pwd'),
            'code' => $request->input('code'),
            //'inviter' => isset($referee) ? $referee : '',
            'company_name' => $request->input('name'),//公司名称
            'ent_type' => json_encode(array_filter(explode(',', $request->input('company_type')))), //公司类型
            //'business_trade' => json_encode(array_filter(explode(',', $request->input('business')))),//主营行业
            //'business_product' => json_encode(array_filter($request->input('zhuyingchanpin'))),//主营产品
            'contact_person' => $request->input('contacts'),//联系人
            //'contact_sex' => intval($request->input('sex')),//联系人性别
            'company_tel' => $request->input('seat_tel') ? $request->input('seat_tel') : '',//公司电话
            'organization_code' => $request->input('organizationCode'),//组织机构代码
            'licence_type' => $request->input('licence_type'),//营业执照类型
        ];

        if ('multi' == $request->input('licence_type')) {
            $params['agnet_licence'] = $request->input('business_license');
            $params['tax_certificate'] = $request->input('tax_certificate');
            $params['organization_code_certificate'] = $request->input('code_certificate');
        }else{
            $params['agnet_licence'] = $request->input('multi_license');
            $params['tax_certificate'] = '';
            $params['organization_code_certificate'] = '';
        }

        $data = http_web($this->api_url['companyregister'])->send($params);

        return $data;

    }





    /*
    * 个人注册信息提交
    */
    public function personalRegisterAction(Request $request)
    {
        $this->validate($this->request, [
            'personal_contacts' => 'required|string',
            'personal_phone' => 'required|string',
            'personal_code' => 'required|string',
            'personal_pwd' => 'required|string',
            'agree' => 'required|string',
        ]);


        //验证验证码是否填写正确
        $param_code = ['phone' => $request->input('personal_phone'),'code' => $request->input('personal_code')];
        $data_code = http_web($this->api_url['verifycode'])->send($param_code);
        if($data_code['code'] != 0){
            return $data_code;
        }
        //参数
        $personal_referee = $request->input('personal_referee');
        $params = [
            'phone' => $request->input('personal_phone'),
            'name' => $request->input('personal_contacts'),
            'pwd' => $request->input('personal_pwd'),
            'code' => $request->input('personal_code'),
            'inviter' => isset($personal_referee) ? $personal_referee : '',
        ];
        $data = http_web($this->api_url['personalregister'])->send($params);

        return $data;

    }






    /**
     * 退出操作
     */
    public function logoutAction(Request $request)
    {
        $request->session()->flush();
        Cookie::queue('carts_data_arr', null , -1); // 销毁
        Cookie::queue('items_data_arr', null , -1); // 销毁
        return redirect('/');
    }







}